package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wanghaotian
 * time:2022/12/15,0015 12:10
 * description:登录功能加验证码
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/admin/auth")
public class AdminAuthController {

    @Autowired
    private DtsRoleService roleService;

    @Autowired
    private DtsPermissionService permissionService;

    @GetMapping("/captchaImage")
    public Object captchaImage() throws Exception{
        //生成验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(1);
        //生成uuid
        String uuid = UUID.randomUUID().toString();
        //存到内存
        CaptchaCodeManager.addToCache(uuid, verifyCode, 10);
        //生成图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(111, 36, outputStream, verifyCode);
        //封装数据
        Map<String,Object> data = new HashMap<>();
        data.put("img", Base64.encode(outputStream.toByteArray()));
        data.put("uuid", uuid);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/login")
    public Object login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        String code = map.get("code");
        String uuid = map.get("uuid");
        //获取缓存中的验证码
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);

        if(StringUtils.isEmpty(code) || !code.equalsIgnoreCase(cachedCaptcha)){
            return ResponseUtil.fail(-1, "验证码错误");
        }
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok(subject.getSession().getId());
    }

    @GetMapping("/info")
    public Object info(){
        Subject subject  = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        String username = admin.getUsername();
        String avatar = admin.getAvatar();
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.findRoleByRolesId(roleIds);
        Set<String> perms = permissionService.findPermsByRolesId(roleIds);
        Map<String,Object> data = new HashMap<>();
        data.put("roles", roles);
        data.put("name", username);
        data.put("perms", perms);
        data.put("avatar", avatar);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseUtil.ok();
    }
}
